package com.wuqing;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

/**
 * @author wuqing
 * @date 2020/8/6
 */
@Activate(group = {CommonConstants.CONSUMER}, value = "ipFilter")
public class DubboTransportFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String ip = DubboTransportFilter.IpContext.getIp();
        RpcContext.getContext().setAttachment("ip", ip);

        long start = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        System.out.println("ip=" + ip + ",调用接口耗时cost=" + (System.currentTimeMillis() - start) + "ms");
        return result;
    }

    public static class IpContext {

        private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<String>();

        public static String getIp() {
            return ipThreadLocal.get();
        }

        public static void setIp(String ip) {
            ipThreadLocal.set(ip);
        }

        public static void release() {
            ipThreadLocal.remove();
        }
    }

}